import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/core/models/me.dart';
import 'package:mall/core/providers/pages/mine/req_code_model.dart';
import 'package:mall/core/providers/pages/mine/user_mobile_update_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/components/count_down_text.dart';
import 'package:provider/provider.dart';

class UserMobilePage extends StatelessWidget {
  static const routeName = '/UserMobilePage';
  final Me args;

  UserMobilePage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => UserMobileUpdateModel(Provider.of(context, listen: false), args),
      child: Scaffold(
        appBar: AppBar(
          title: Text('绑定手机号码'),
        ),
        body: SingleChildScrollView(
          child: Builder(
            builder: (context) {
              UserMobileUpdateModel model = Provider.of(context, listen: false);
              return Column(
                children: <Widget>[
                  _WrapContainer(
                    child: TextFormField(
                      decoration: InputDecoration(
                        hintText: '要绑定的新手机号码',
                      ),
                      keyboardType: TextInputType.phone,
                      onChanged: (value) {
                        model.mobile = value;
                      },
                    ),
                  ),
                  SizedBox(height: 10),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: _WrapContainer(
                          child: TextFormField(
                            decoration: InputDecoration(
                              hintText: '新手机接收的验证码',
                            ),
                            onChanged: (value) {
                              model.checkCode = value;
                            },
                          ),
                        ),
                      ),
                      SizedBox(width: 1),
                      Container(
                        alignment: Alignment.center,
                        color: Colors.white,
                        width: 118,
                        height: 50,
                        child: ChangeNotifierProvider(
                          create: (context) => ReqCodeModel(Provider.of(context, listen: false)),
                          child: Consumer<ReqCodeModel>(
                            builder: (context, model, child) {
                              switch (model.viewState) {
                                case ViewState.busy:
                                  return FlatButton(
                                    onPressed: null,
                                    child: SizedBox(
                                      width: 14,
                                      height: 14,
                                      child: CircularProgressIndicator(),
                                    ),
                                  );
                                case ViewState.success:
                                  return FlatButton(
                                    onPressed: null,
                                    child: CountDownText(
                                      function: () {
                                        model.viewState = ViewState.idle;
                                      },
                                      style: TextStyle(color: Colors.grey, fontSize: 16),
                                    ),
                                  );
                                default:
                                  return FlatButton(
                                    onPressed: () {
                                      _onNewCodeClicked(context);
                                    },
                                    child: Text(
                                      '发送验证码',
                                      style: TextStyle(color: Colors.grey, fontSize: 16),
                                    ),
                                  );
                              }
                            },
                          ),
                        ),
                      ),
                    ],
                  ),
                  if (args.mobile != null) ...[
                    SizedBox(height: 10),
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: _WrapContainer(
                            child: TextFormField(
                              decoration: InputDecoration(
                                hintText: '原手机接收的验证码',
                              ),
                              onChanged: (value) {
                                model.verifyCode = value;
                              },
                            ),
                          ),
                        ),
                        SizedBox(width: 1),
                        Container(
                          alignment: Alignment.center,
                          color: Colors.white,
                          width: 118,
                          height: 50,
                          child: ChangeNotifierProvider(
                            create: (context) => ReqCodeModel(Provider.of(context, listen: false)),
                            child: Consumer<ReqCodeModel>(
                              builder: (context, model, child) {
                                switch (model.viewState) {
                                  case ViewState.busy:
                                    return FlatButton(
                                      onPressed: null,
                                      child: SizedBox(
                                        width: 14,
                                        height: 14,
                                        child: CircularProgressIndicator(),
                                      ),
                                    );
                                  case ViewState.success:
                                    return FlatButton(
                                      onPressed: null,
                                      child: CountDownText(
                                        function: () {
                                          model.viewState = ViewState.idle;
                                        },
                                        style: TextStyle(color: Colors.grey, fontSize: 16),
                                      ),
                                    );
                                  default:
                                    return FlatButton(
                                      onPressed: () {
                                        _onOldCodeClicked(context);
                                      },
                                      child: Text(
                                        '发送验证码',
                                        style: TextStyle(color: Colors.grey, fontSize: 16),
                                      ),
                                    );
                                }
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                    Container(
                      alignment: Alignment.centerLeft,
                      margin: EdgeInsets.only(left: 16, top: 10),
                      child: Text(
                        '原手机号:${args.mobile.replaceRange(3, 7, '****')}',
                        style: TextStyle(color: Colors.grey),
                      ),
                    )
                  ],
                  Container(
                    margin: EdgeInsets.all(16),
                    width: double.maxFinite,
                    child: Consumer<UserMobileUpdateModel>(
                      builder: (context, model, child) {
                        switch (model.viewState) {
                          case ViewState.busy:
                            return RaisedButton(
                              onPressed: null,
                              child: SizedBox(
                                child: CircularProgressIndicator(),
                              ),
                            );
                          default:
                            return RaisedButton(
                              onPressed: () {
                                _onUpdateClicked(context);
                              },
                              child: Text(
                                '确定',
                                style: TextStyle(fontSize: 18),
                              ),
                            );
                        }
                      },
                    ),
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  void _onNewCodeClicked(BuildContext context) async {
    UserMobileUpdateModel userMobileUpdateModel = Provider.of(context, listen: false);
    ReqCodeModel reqCodeModel = Provider.of(context, listen: false);
    var viewState = await reqCodeModel.reqCode(
      ReqCodeModel.UPDATE_MOBILE,
      userMobileUpdateModel.mobile,
      userId: userMobileUpdateModel.me.userId,
    );
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(reqCodeModel.errorMessage);
        break;
      default:
        EasyLoading.showToast('短信已发送');
        break;
    }
  }

  void _onOldCodeClicked(BuildContext context) async {
    ReqCodeModel reqCodeModel = Provider.of(context, listen: false);
    var viewState = await reqCodeModel.reqCode(
      ReqCodeModel.UPDATE_MOBILE,
      args.mobile,
      userId: args.userId,
    );
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(reqCodeModel.errorMessage);
        break;
      default:
        EasyLoading.showToast('短信已发送');
        break;
    }
  }

  void _onUpdateClicked(BuildContext context) async {
    UserMobileUpdateModel model = Provider.of(context, listen: false);
    var viewState = await model.userMobileUpdate();
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(model.errorMessage);
        break;
      default:
        EasyLoading.showToast('更新成功');
        Navigator.of(context).pop(model.mobile);
        break;
    }
  }
}

class _WrapContainer extends StatelessWidget {
  final EdgeInsetsGeometry margin;
  final Widget child;

  _WrapContainer({
    Key key,
    this.margin,
    this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(horizontal: 16),
      color: Colors.white,
      height: 50,
      margin: margin,
      child: child,
    );
  }
}
